package com.centaline.androidsalesblog.activities.map;

import android.support.v7.widget.AppCompatTextView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MapViewLayoutParams;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.application.MyLocation;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.iml.BaiduMarkerClick;
import com.centaline.androidsalesblog.overlay.local.AroundEstateOverlay;
import com.centaline.androidsalesblog.overlay.local.AroundPoiOverlay;
import com.centaline.androidsalesblog.rx.map.RxMap;
import com.trello.rxlifecycle.ActivityEvent;

import java.util.Locale;

import rx.functions.Action1;

/**
 * 地图详情-周边功能
 * <p>
 * Created by Lihq on 2016/1/29.
 */
public class AroundMapActivity extends BaseActivity implements BaiduMap.OnMapLoadedCallback,
        OnGetPoiSearchResultListener,
        View.OnClickListener {

    private MapView mapView;
    private LinearLayout ll_bus, ll_metro, ll_school, ll_est, ll_hospital, ll_market, ll_bank;
    private BaiduMap baiduMap;

    private LocationClient locationClient;
    private PoiSearch mPoiSearch;
    private InfoWindow estInfoWindow;
    private View poiView;

    private int lastPosition = -1;

    private AroundPoiOverlay aroundPoiOverlay;
    private AroundEstateOverlay aroundEstateOverlay;
    private LatLng estLatLng;
    private String name;
    private boolean showPoiView;

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        mapView.onDestroy();
        super.onDestroy();
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_map_detail;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar(R.string.title_ip_around);
        mapView = (MapView) findViewById(R.id.mapView);
        ll_bus = (LinearLayout) findViewById(R.id.ll_bus);
        ll_metro = (LinearLayout) findViewById(R.id.ll_metro);
        ll_school = (LinearLayout) findViewById(R.id.ll_school);
        ll_est = (LinearLayout) findViewById(R.id.ll_est);
        ll_hospital = (LinearLayout) findViewById(R.id.ll_hospital);
        ll_market = (LinearLayout) findViewById(R.id.ll_market);
        ll_bank = (LinearLayout) findViewById(R.id.ll_bank);
    }

    @Override
    protected void initViews() {
        baiduMap = mapView.getMap();
        UiSettings uiSettings = baiduMap.getUiSettings();
        uiSettings.setCompassEnabled(true);
        uiSettings.setOverlookingGesturesEnabled(false);
        uiSettings.setRotateGesturesEnabled(false);
        baiduMap.setMyLocationEnabled(true);
        baiduMap.setOnMapLoadedCallback(this);

        locationClient = MyLocation.getLocationClient();
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);

        poiView = LayoutInflater.from(this).inflate(R.layout.layout_map_around_poi, null);
        poiView.setVisibility(View.GONE);
        mapView.addView(poiView);

        estLatLng = getIntent().getParcelableExtra(ExtraConstant.LatLng);
        name = getIntent().getStringExtra(ExtraConstant.MAP_NAME);

        View estView = LayoutInflater.from(this).inflate(R.layout.layout_map_around_estate, null);
        AppCompatTextView atv_name = (AppCompatTextView) estView.findViewById(R.id.atv_name);
        ImageView img_nav = (ImageView) estView.findViewById(R.id.img_nav);
        img_nav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocation();
            }
        });
        atv_name.setText(name);
        estInfoWindow = new InfoWindow(estView, estLatLng, -20);

        aroundEstateOverlay = new AroundEstateOverlay(baiduMap, new BaiduMarkerClick() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                baiduMap.showInfoWindow(estInfoWindow);
                return true;
            }
        });

        aroundPoiOverlay = new AroundPoiOverlay(this, baiduMap, estLatLng, new BaiduMarkerClick() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                baiduMap.hideInfoWindow();
                if (aroundPoiOverlay.getPoiResult() != null) {
                    PoiInfo poiInfo = aroundPoiOverlay.getPoiResult().getAllPoi().get(marker.getExtraInfo().getInt("index"));
                    switch (poiInfo.type) {
                        case BUS_LINE:
                        case BUS_STATION:
                        case SUBWAY_LINE:
                        case SUBWAY_STATION:
                            updatePoiPop(poiInfo, 0);
                            break;
                        default:
                            updatePoiPop(poiInfo, 1);
                            break;
                    }
                }
                return false;
            }
        });
        baiduMap.setOnMarkerClickListener(aroundPoiOverlay);

        RxMap.location(locationClient, false)
                .compose(this.<BDLocation>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<BDLocation>() {
                    @Override
                    public void call(BDLocation bdLocation) {
                        cancelLoadingDialog();
                        switch (bdLocation.getLocType()) {
                            case 61:
                            case 161:
                                NaviParaOption naviParaOption = new NaviParaOption();
                                naviParaOption.startPoint(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()))
                                        .endPoint(estLatLng);
                                BaiduMapNavigation.openBaiduMapNavi(naviParaOption, AroundMapActivity.this);
                                break;
                            default:
                                snack("定位失败");
                                break;
                        }
                    }
                });
    }

    @Override
    public void onMapLoaded() {
        aroundEstateOverlay.addToMap(estLatLng);
        baiduMap.showInfoWindow(estInfoWindow);
    }

    private void updatePoiPop(PoiInfo poiInfo, int type) {
        AppCompatTextView atv_name = (AppCompatTextView) poiView.findViewById(R.id.atv_name);
        atv_name.setText(type == 0 ?
                String.format(Locale.CHINA, "%s\n%s", poiInfo.name, poiInfo.address) :
                String.format("%s(%s)", poiInfo.name, poiInfo.address));
        poiView.setVisibility(View.VISIBLE);
        MapViewLayoutParams params = new MapViewLayoutParams.Builder()
                .width(MapViewLayoutParams.WRAP_CONTENT)
                .height(MapViewLayoutParams.WRAP_CONTENT)
                .layoutMode(MapViewLayoutParams.ELayoutMode.mapMode)
                .position(poiInfo.location)
                .yOffset(-40)
                .build();
        mapView.updateViewLayout(poiView, params);
        showPoiView = true;
    }


    /**
     * 开始定位
     */
    private void startLocation() {
        showLoadingDialog();
        locationClient.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_bus:
                select(0, false);
                search("公交");
                break;
            case R.id.ll_metro:
                select(1, false);
                search("地铁");
                break;
            case R.id.ll_school:
                select(2, false);
                search("学校");
                break;
            case R.id.ll_est:
                select(3, false);
                search("楼盘");
                break;
            case R.id.ll_hospital:
                select(4, false);
                search("医院");
                break;
            case R.id.ll_market:
                select(5, false);
                search("超市");
                break;
            case R.id.ll_bank:
                select(6, false);
                search("银行");
                break;
            default:
                break;
        }
    }

    private void search(String key) {
        if (showPoiView) {
            poiView.setVisibility(View.GONE);
            showPoiView = false;
        }
        showLoadingDialog();
        mPoiSearch.searchNearby(new PoiNearbySearchOption()
                .keyword(key)
                .location(estLatLng)
                .radius(5000)
                .sortType(PoiSortType.distance_from_near_to_far));
    }

    private void select(int pos, boolean enable) {
        switch (pos) {
            case 0:
                ll_bus.setEnabled(enable);
                break;
            case 1:
                ll_metro.setEnabled(enable);
                break;
            case 2:
                ll_school.setEnabled(enable);
                break;
            case 3:
                ll_est.setEnabled(enable);
                break;
            case 4:
                ll_hospital.setEnabled(enable);
                break;
            case 5:
                ll_market.setEnabled(enable);
                break;
            case 6:
                ll_bank.setEnabled(enable);
                break;
        }
        if (!enable) {
            select(lastPosition, true);
            lastPosition = pos;
        }
    }

    @Override
    public void onGetPoiResult(PoiResult poiResult) {
        cancelLoadingDialog();
        if (poiResult == null
                || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            snack("抱歉，未找到结果");
            return;
        }
        if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
            int resource;
            switch (lastPosition) {
                case 0:
                    resource = R.drawable.map_bus;
                    break;
                case 1:
                    resource = R.drawable.map_metro;
                    break;
                case 2:
                    resource = R.drawable.map_school;
                    break;
                case 3:
                    resource = R.drawable.map_est;
                    break;
                case 4:
                    resource = R.drawable.map_hospital;
                    break;
                case 5:
                    resource = R.drawable.map_market;
                    break;
                case 6:
                    resource = R.drawable.map_bank;
                    break;
                default:
                    resource = 0;
                    break;
            }
            aroundPoiOverlay.setPoiResult(poiResult, resource);
            aroundPoiOverlay.addToMap();
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
        if (poiDetailResult.error != SearchResult.ERRORNO.NO_ERROR) {
            snack("抱歉，未找到结果");
        }
    }
}
